package com.jiantong.web.open.app.work;

import com.jiantong.common.util.UserUtil;
import com.jiantong.user.ext.LoginUser;
import com.jiantong.user.model.BreedFactory;
import com.jiantong.user.service.BreedFactoryReadService;
import com.jiantong.web.core.enums.ExceptionCode;
import com.jiantong.work.model.MaterialPurchaseRecord;
import com.jiantong.work.service.MaterialPurchaseRecordReadService;
import com.jiantong.work.service.MaterialPurchaseRecordWriteService;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import io.terminus.pampas.openplatform.annotations.OpenBean;
import io.terminus.pampas.openplatform.annotations.OpenMethod;
import io.terminus.pampas.openplatform.exceptions.OPClientException;
import io.terminus.pampas.openplatform.exceptions.OPServerException;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Strings;
import org.joda.time.DateTime;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.*;

/**
 * 原料采购记录
 * Created by maowenije on 2017/4/17.
 */
@Slf4j
@OpenBean
public class MaterialPurchaseRecordApis {
    @RpcConsumer
    private MaterialPurchaseRecordReadService materialPurchaseRecordReadService;

    @RpcConsumer
    private MaterialPurchaseRecordWriteService materialPurchaseRecordWriteService;

    @RpcConsumer
    private BreedFactoryReadService breedFactoryReadService;

    /**
     * 根据id查询
     * @param id 主键
     * @return  原料采购记录
     */
    @OpenMethod(
            key = "find.material.purchase.by.id",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET
    )
    public MaterialPurchaseRecord findMaterialPurchaseRecordById(Long id){
        if (id==null){
            log.error("is should be not null");
            throw new OPClientException(ExceptionCode.ID_NOT_EXIST.value(),"is should be not null");
        }
        Response<MaterialPurchaseRecord> response = materialPurchaseRecordReadService.findMaterialPurchaseRecordById(id);
        if(!response.isSuccess()){
            log.error("failed to find materialPurchaseRecord , cause : {}", response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),response.getError());
        }
        return response.getResult();
    }

    /**
     * 根据状态(status)/养殖场id分页查询原料采购记录
     * @param pageNo
     * @param pageSize
     * @param breedFactoryId
     * @param status 是否生效
     * @return
     */
    @OpenMethod(
            key = "paging.material.purchase",
            paramNames = {"pageNo","pageSize","breedFactoryId","status"},
            httpMethods = RequestMethod.GET
    )
    public Paging<MaterialPurchaseRecord> pagingMaterialPurchaseRecord(Integer pageNo, Integer pageSize,Long breedFactoryId, Integer status){
        if (breedFactoryId == null){
            log.error("breedFactoryId can not be empty");
            throw new OPClientException(ExceptionCode.PARAMETER_NOT_EXIST.value(),"breedFactoryId can not be empty");
        }
        Response<Paging<MaterialPurchaseRecord>> response = materialPurchaseRecordReadService.pagingMaterialPurchaseRecordByStatus(pageNo,pageSize,breedFactoryId,status);
        if(!response.isSuccess()){
            log.error("failed to paging materialPurchaseRecord farm , cause : {}", response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),response.getError());
        }
        return response.getResult();
    }

    /**
     * 分页查询当前登录人所管理的养殖场下的所有已生效的原料采购记录.
     * @param pageNo
     * @param pageSize
     * @return
     */
    @OpenMethod(
            key = "paging.material.purchase.by.user",
            paramNames = {"pageNo","pageSize"},
            httpMethods = RequestMethod.GET
    )
    public Paging<MaterialPurchaseRecord> pagingMaterialPurchaseRecordByUser(Integer pageNo, Integer pageSize){
        Response<Paging<MaterialPurchaseRecord>> response = materialPurchaseRecordReadService.pagingMaterialPurchaseRecordByUser(pageNo,pageSize);
        if(!response.isSuccess()){
            log.error("failed to paging materialPurchaseRecord farm , cause : {}", response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),response.getError());
        }
        return response.getResult();
    }

    /**
     * 创建原料采购记录
     * @param materialPurchaseRecord 原料采购记录
     * @param toStatus 到状态
     * @return
     */
    @OpenMethod(
            key = "create.material.purchase",
            paramNames = {"materialPurchase","toStatus"},
            httpMethods = RequestMethod.POST
    )
    public Map<String , Object> createMaterialPurchaseRecord(MaterialPurchaseRecord materialPurchaseRecord , Integer toStatus){
        Response<Map<String , Object>> response = materialPurchaseRecordWriteService.create(materialPurchaseRecord,toStatus);
        if(!response.isSuccess()){
            log.error("failed to create materialPurchaseRecord, cause : {}",materialPurchaseRecord,toStatus,response.getError());
            throw new OPServerException(ExceptionCode.DATA_WRITE_FAIL.value(),response.getError());
        }
        return response.getResult();
    }

    /**
     * 更新原料采购记录
     * @param materialPurchaseRecord
     * @param toStatus
     * @return
     */
    @OpenMethod(
            key = "update.material.purchase",
            paramNames = {"materialPurchase","toStatus"},
            httpMethods = RequestMethod.PUT
    )
    public  Map<String , Object> updateMaterialPurchaseRecord(MaterialPurchaseRecord materialPurchaseRecord , Integer toStatus){
        if(materialPurchaseRecord.getId() == null){
            log.error("failed to update materialPurchaseRecord error = {}, cause : {}", materialPurchaseRecord,materialPurchaseRecord.getId());
            throw new OPClientException(ExceptionCode.ID_NOT_EXIST.value(),"materialPurchaseRecord.id can not be empty");
        }

        Response<Map<String , Object>> statusResponse = materialPurchaseRecordReadService.findStatusById(materialPurchaseRecord.getId());
        if(statusResponse.isSuccess() && !statusResponse.getResult().get("status").equals(materialPurchaseRecord.getStatus())){
            log.error("materialPurchaseRecord is already submitted error = {}, cause : {}", materialPurchaseRecord.getStatus(),statusResponse.getResult().get("status"));
            throw new OPClientException(ExceptionCode.DATA_NOT_FOUND.value(),"this.report.is.already.submitted");
        }

        Response<Map<String , Object>> response = materialPurchaseRecordWriteService.update(materialPurchaseRecord,toStatus);
        if(!response.isSuccess()){
            log.error("failed to update quarantineCenterHarmless error = {}, cause : {}", materialPurchaseRecord, response.getError());
            throw new OPServerException(ExceptionCode.DATA_UPDATE_FAIL.value(),response.getError());
        }
        return response.getResult();
    }

    /**
     * 根据养殖场id或创建时间段分页查询
     * @param pageNo
     * @param pageSize
     * @param breedFactoryId
     * @param fromDate
     * @param toDate
     * @return
     */
    @OpenMethod(
            key = "paging.status.material.purchase",
            paramNames = {"pageNo", "pageSize","breedFactoryId","breedType", "fromDate", "toDate"},
            httpMethods = RequestMethod.GET)
    public Paging<MaterialPurchaseRecord> pagingMaterialPurchaseRecord(Integer pageNo,
                                                                           Integer pageSize,
                                                                           Long breedFactoryId,
                                                                       Integer breedType,
                                                                           String fromDate,
                                                                           String toDate) {
        Date start = null;
        if (!Strings.isNullOrEmpty(fromDate)) {
            start = DateTime.parse(fromDate).toDate();
        }

        Date end = null;
        if (!Strings.isNullOrEmpty(toDate)) {
            end = DateTime.parse(toDate).toDate();
        }
        Response<Paging<MaterialPurchaseRecord>> resp = materialPurchaseRecordReadService.
                pagingMaterialPurchaseRecordGqv (pageNo, pageSize, breedFactoryId,breedType, start, end);
        if (!resp.isSuccess()) {
            log.error("failed to paging material record{}, cause : {}", resp.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),resp.getError());
        }
        return resp.getResult();
    }
}
